import type { FC } from 'react';
import style from './index.less';
import React, { Fragment, useState, useEffect } from 'react';
import Header from './Header';
import { history, useModel } from 'umi';
import GoHome from '@/components/GoHome';
import {
  Button,
  Divider,
  Input,
  message,
  Modal,
  Pagination,
  Select,
  Table,
  Tabs,
  Upload,
  Image
} from 'antd';
import {
  ConsoleSqlOutlined,
  GatewayOutlined,
  LoadingOutlined,
  PlusOutlined,
  ReadOutlined,
  SmileTwoTone,
  SearchOutlined,
  TeamOutlined,
  TranslationOutlined
} from '@ant-design/icons';
import { getBookList, getBookTop, saveBook, saveBookVisitNum } from './service';
interface Props {}
const { TabPane } = Tabs;
const UserDetail: FC<Props> = () => {
  const [visible, setVisible] = useState<boolean>(false);
  const [loading, setLoading] = useState(false);
  const [bookList, setBookList] = useState([]);
  const [submitData, setSubmitData] = useState({
    title: '',
    author: '',
    img_url: '',
    file_url: '',
    type: '',
  });
  const [pagination, setPagination] = useState({
    currentPage: 1,
    pageSize: 8,
    total: 0,
  });
  const [search, setSearch] = useState({
    type: '',
    author: '',
    title: '',
  });
  const [bookTop, setBookTop] = useState([]);

  const getBookTopList = async () => {
    const { data } = await getBookTop({});
    console.log(data, '11dssdsd1122');
    setBookTop(data);
  };

  const handleOK = async () => {
    console.log(submitData, 'submitDatasubmitData');
    const { code } = await saveBook(submitData);
    code === 1000 ? message.success('发布成功') : message.error('失败');
    setSubmitData({
      title: '',
      author: '',
      img_url: '',
      file_url: '',
      type: '',
    });
    setVisible(false);
    BookList();
  };
  const handleCancel = () => {
    setVisible(false);
  };
  // 上传前
  const beforeUpload = (file: any) => {
    console.log(file.type);
  };
  // 转为base64
  const getBase64 = (img: Blob, callback: any) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };
  // 上传文件
  const handleChange = (info: any) => {
    console.log(info.file, 'info');
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      getBase64(info.file.originFileObj, (file_url: any) => {
        // setImageUrl(imageUrl);
        setSubmitData({ ...submitData, file_url: info.file.response.url });
        // setSubmitParams({ ...submitParams, cover: info.file.response.url });
        setLoading(false);
      });
    }
  };
  const handleChangeImage = (info: any) => {
    console.log(info.file, 'info');
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      getBase64(info.file.originFileObj, (file_url: any) => {
        // setImageUrl(imageUrl);
        setSubmitData({ ...submitData, img_url: info.file.response.url });
        // setSubmitParams({ ...submitParams, cover: info.file.response.url });
        setLoading(false);
      });
    }
  };

  const BookList = () => {
    // 查询条件我现在没加
    getBookList({
      ...search,
      pageSize: pagination.pageSize,
      currentPage: pagination.currentPage,
      type: search.type,
    }).then(res => {
      setBookList(res.data);
      setPagination({
        currentPage: res.current,
        total: res.total,
        pageSize: res.pageSize,
      });
    });
  };

  const onChange = (page, pageSize) => {
    getBookList({ currentPage: page, pageSize }).then(res => {
      setBookList(res.data);
      setPagination({
        currentPage: res.current,
        total: res.total,
        pageSize: res.pageSize,
      });
    });
  };

  const { Option } = Select;
  useEffect(() => {
    BookList();
    getBookTopList();
  }, [search]);
  const openUpload = param => {
    window.open(param);
  };

  return (
    <div style={{ height: '1000px', background: 'white' }}>
      <div className={style.container}>
        <div className={style.container_head}>
          <div className={style.marginTop}>
            <div className={style.title}>书籍分享社区</div>

            <div className={style.mine}>
              <Input
                placeholder="搜索🔍书籍名称、书籍作者"
                style={{ borderRadius: 20 }}
                onChange={e => {
                  setSearch({ ...search, title: e.target.value, author: e.target.value });
                  console.log('我是现在输入框中的', e.target.value);
                }}
                suffix={(
                  <Button
                    type="primary"
                    shape="circle"
                    icon={<SearchOutlined />}
                    onClick={e => {
                      console.log(e);
                    }}
                  />
                )}
              />
            </div>
            <Button
              onClick={() => {
                setVisible(true);
              }}
              type="primary"
              style={{ height: '50px', fontSize: '20px', marginRight: '10%', marginTop: '10px' }}
            >
              我要分享图书
            </Button>
          </div>
        </div>
      </div>
      <div className={style.container} style={{ marginTop: '20px', height: '720px' }}>
        <div className={style.left}>
          <GoHome />
        </div>
        <div className={style.main}>
          <div className={style.tab_con}>
            <Tabs
              defaultActiveKey={'全部'}
              // 选择其他Tab
              onChange={key => {
                setSearch({
                  ...search,
                  type: key,
                });
              }}
              style={{ marginTop: '10px', paddingLeft: '10px' }}
            >
              <TabPane
                tab={(
                  <span>
                    {/* <TeamOutlined /> */}
                    全部
                  </span>
                )}
                key=""
              />
              <TabPane
                tab={(
                  <span>
                    <TeamOutlined />
                    前端
                  </span>
                )}
                key="前端"
              />
              <TabPane
                tab={(
                  <span>
                    <ConsoleSqlOutlined />
                    后端
                  </span>
                )}
                key="后端"
              />
              <TabPane
                tab={(
                  <span>
                    <GatewayOutlined />
                    人工智能
                  </span>
                )}
                key="人工智能"
              />
              <TabPane
                tab={(
                  <span>
                    <ReadOutlined />
                    机器学习
                  </span>
                )}
                key="机器学习"
              />
              <TabPane
                tab={(
                  <span>
                    <TranslationOutlined />
                    Python
                  </span>
                )}
                key="Python"
              />
            </Tabs>
          </div>
          <div className={style.main}>
            <div title="入门书籍推" className={style.card}>
              {bookList.map((item, index) => (
                <div className={style.box} key={item.id}>
                  <div className={style.img}>
                    <Image width={200} height={180} src={item.img_url} />
                  </div>
                  <div className={style.text}>
                    <div>
                      <span className={style.book}>{item.title}</span>
                    </div>
                    <div>
                      <span className={style.name}>{item.author}</span>
                    </div>
                    <div className={style.remark}>
                      <Button
                        type="primary"
                        style={{ height: 28, padding: 3, marginLeft: 4 }}
                        onClick={() => {
                          console.log('我点按钮');
                          openUpload(item.file_url);
                          saveBookVisitNum({
                            title: item.title,
                            author: item.author,
                            file_url: item.file_url,
                            id: item.id,
                          });
                        }}
                      >
                        查看详情
                      </Button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <Pagination
            current={pagination.currentPage}
            onChange={onChange}
            total={pagination.total}
            pageSize={pagination.pageSize}
            style={{ marginLeft: '35%' }}
          />
        </div>

        <div className={style.right}>
          <div className={style.box}>
            <div className={style.title}>热门书籍排行榜</div>
            <Divider />
            {bookTop.map((item, index) => (
              <div className={style.book}>
                <div className={style.con}>
                  <div className={style.booknumber}>{index + 1}.</div>
                  <div className={style.bookname}>《{item.title}》</div>
                </div>
                <div className={style.remark}>{item.author}</div>
              </div>
            ))}
            {/* 这里我只是试一下效果 你再把你的注释放开   */}
            {/* {
                bookList.map((item,index)=>(
                  <span href={item.file_url} onClick={()=>{openUpload(item.file_url)}}>{item.title}</span>
                ))
            } */}
          </div>
        </div>
      </div>

      <Modal title="上传文件" visible={visible} onOk={handleOK} onCancel={handleCancel}>
        文章标题
        <Input
          onChange={e => {
            setSubmitData({ ...submitData, title: e.target.value });
          }}
        />
        文章作者
        <Input
          onChange={e => {
            setSubmitData({ ...submitData, author: e.target.value });
          }}
        />
        上传封面
        <Upload
          // 对应后端的 ctx.request.files.file
          name="file"
          listType="picture-card"
          className="avatar-uploader"
          showUploadList={false}
          action="/api/client/Upload"
          beforeUpload={beforeUpload}
          onChange={handleChangeImage}
        >
          {submitData.img_url ? (
            <img
              src={submitData.img_url}
              alt="avatar"
              style={{ width: '100%', marginTop: '10px' }}
            />
          ) : (
            <div>
              {loading ? <LoadingOutlined /> : <PlusOutlined />}
              <div style={{ marginTop: 8 }}>Upload</div>
            </div>
          )}
          {/* <div style={{ marginTop: 8 }}>Upload</div> */}
        </Upload>
        上传文件
        <Upload
          // 对应后端的 ctx.request.files.file
          name="file"
          listType="text"
          className="avatar-uploader"
          showUploadList={false}
          action="/api/client/Upload"
          beforeUpload={beforeUpload}
          onChange={handleChange}
        >
          <Button type="primary" style={{ marginTop: 8, marginLeft: 10 }}>
            请上传相关PDF文件
          </Button>
          {/* <div style={{ marginTop: 8 }}>Upload</div> */}
        </Upload>
        <div>
          书籍类型
          <Select
            style={{ width: 200, marginTop: 10, marginLeft: 10 }}
            onChange={e => {
              console.log(e, '我是选中的');
              setSubmitData({ ...submitData, type: e });
            }}
          >
            {/* <Option value="">全部</Option> */}
            <Option value="前端">前端</Option>
            <Option value="后端">后端</Option>
            <Option value="人工智能">人工智能</Option>
            <Option value="机器学习">机器学习</Option>
            <Option value="Python">Python</Option>
          </Select>
        </div>
      </Modal>
    </div>
  );
};

export default UserDetail;
